//
//  LinePay.swift
//  tappay_charge
//
//  Created by Warren L on 2024/7/19.
//

import TPDirect

typealias LinePayCommonCallback = (TappaySdkCommonResult) -> Void

typealias LinePayPaymentCallback = (TappayPaymentResult) -> Void

class LinePay : NSObject {
    var linePay: TPDLinePay!
    
    /// 支付回調
    var onLinePayResult: LinePayPaymentCallback?
    
    /// 獲取Line Pay Prime
    func getLinePayPrime(
        returnUrl: String,
        callback: LinePayPaymentCallback?
    ) {
        
        linePay = TPDLinePay.setup(withReturnUrl: returnUrl)
        linePay
            .onSuccessCallback { prime in
                let successRetult = TappayPaymentResult(success: true, status: nil, message: "Get Line Pay prime was successful", prime: prime)
                callback?(successRetult)
            }
            .onFailureCallback { status, message in
                let errorResult = TappayPaymentResult(success: false, status: status, message: message, prime: nil)
                callback?(errorResult)
            }
            .getPrime()
    }
    
    /// 跳轉至Line Pay進行支付
    func redirectLinePay(
        paymentUrl: String,
        callback: LinePayPaymentCallback?
    ) {
        guard let linePay = linePay else {
            let errorResult = TappayPaymentResult(success: false, status: nil, message: "Please getLinePayPrime first", prime: nil)
            callback?(errorResult)
            return
        }
        
        self.onLinePayResult = callback
        
        
        linePay.redirect(paymentUrl, with: topViewController()!) { result in
            
            print("stauts : \(result.status) , recTradeId : \(result.recTradeId ?? "") , bankTransactionId : \(result.bankTransactionId ?? "") , order_number : \(result.orderNumber ?? "")")
            
            if (result.status == 0) {   /// 0：成功
                let successResult = TappayPaymentResult(success: true, status: nil, message: "Redirect Line Pay was successful", prime: nil)
                callback?(successResult)
            } else {
                let errorResult = TappayPaymentResult(success: false, status: result.status, message: "Redirect Line Pay was failure", prime: nil)
                callback?(errorResult)
            }
        }
    }
    
    func topViewController(_ base: UIViewController? = UIApplication.rootKeyWindow?.rootViewController) -> UIViewController? {
        if let nav = base as? UINavigationController {
            return topViewController(nav.visibleViewController)
        }
        
        if let tab = base as? UITabBarController, let selected = tab.selectedViewController {
            return topViewController(selected)
        }
        
        if let presented = base?.presentedViewController {
            return topViewController(presented)
        }
        
        return base
    }
}

extension UIApplication {
    static var rootKeyWindow: UIWindow? {
        if #available(iOS 13.0, *) {
            return UIApplication.shared.windows.first { $0.isKeyWindow }
        }
        return UIApplication.shared.keyWindow
    }
}
